import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store/index'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 100000 // request timeout
})
// request请求拦截    前置拦截
service.interceptors.request.use(
  config => {
    store.commit('toShow')
    // 将token数据默认添加到请求头中
    if (store.state.token) {
      config.headers['Authorization'] = store.state.token
      console.log('请求头添加：' + store.state.token)
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response拦截器   后置拦截
service.interceptors.response.use(response => {
  const da = response.data
  store.commit('toHide')
  // 出现异常
  if (da.code >= 40001 && da.code <= 50000) {
    Message({
      message: da.msg,
      type: 'error',
      duration: 3000
    })
    throw new Error()
  } else {
    return response
  }
})

export default service
